<?php

/**
 *
 * Copyright (c) 2011 Tomáš Holub (tomas.holub@webadvice.cz)
 * 
 * @author Tomáš Holub (tomas.holub@webadvice.cz)
 * @package OverFishCMS
 */

namespace OverFish\Model\Mappers;

use Nette;
use OverFish;
use OverFish\Model\Entities\menu as MenuEntity;

class Menu extends Nette\Object implements OverFish\Model\IMapper {

    private $conn;

    public function __construct(\DibiConnection $conn) {
        $this->conn = $conn;
    }
    
    public function delete($item) {
        $this->conn->delete('menu')
            ->where('id = %i', $item->getId())->execute();
    }
    
    public function save($item) {

        if ($item->getId() === NULL) { // insert
            $data = $this->itemToData($item); // vytáhne data z entity a vrátí jako pole
            
            $id = $this->conn->insert('menu', $data)->execute();
            $id = $this->conn->insertId();

            $this->setIdentity($item, $id);

        } else { // update
            $data = $this->itemToData($item); 
            
            $this->conn->update('menu', $data)
                ->where('id = %i', $item->getId())->execute();

        }
    }
    
    
    public function itemToData($item) {
        $data = array();
        
        $data = array(
            "title" => $item->getTitle(),
        );
        
        return $data;
    }
    
    public function find($id) {
        $data = $this->conn->select('*')
                        ->from('menu')
                        ->where('id = %i', $id)->fetch();

        return $this->load($data);
    }

    public function load($data) {
        $item = new MenuEntity();

        if (!$data) {
            return False;
        }

        $this->setIdentity($item, $data->id);

        unset($data['id']);

        $item->setTitle($data->title);
        
        
        

        return $item;
    }

    function findBy(array $values) {
        
    }

    /** předáš tomu pole hodnot, podle kterých má hledat. Vrátí jednu entitu */
    function findOneBy(array $values) {
        
    }

    /** vrátí všechno */
    function findAll() {
        
    }

    private function setIdentity($item, $id) {
        $item->setId($id);

        return $item;
    }

    public function getAllDataSource() {
        return $this->conn->select('*')->from('menu');
    }

}

